package com.lmm.rpc.core.serialization;

import com.google.gson.Gson;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class JsonSerialization implements Serialization{
    private static final Gson gson;
    static {
        gson = new Gson();
    }
    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        if (obj == null){
            throw new NullPointerException();
        }
        byte[] bytes;
        try{
            bytes = gson.toJson(obj).getBytes(StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new SerializationException(e);
        }
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) throws IOException {
        if (data == null){
            throw new NullPointerException();
        }
        T t;
        try{
            String dataJson = new String(data, StandardCharsets.UTF_8);
            t = gson.fromJson(dataJson, clz);
        }catch (Exception e){
            throw new SerializationException(e);
        }
        return t;
    }
}
